#pragma once

#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>

void daemonslf(const char* pathname = nullptr)
{
    //step 1:先将进程变成孤儿进程
    pid_t id = fork();
    if(id>0) exit(0);

    //step 2:将该孤儿进程设置为守护进程
    setsid();

    //step 3:将不要的文件描述符关闭
    int sock = open("/dev/null", O_RDWR);
    if(sock >= 0)
    {
        dup2(sock, 0);
        dup2(sock, 1);
        dup2(sock, 2);
    }
    else
    {
        close(0);
        close(1);
        close(2);
    }

    //step 4:可选项
    if(pathname) chdir(pathname);
}